package com.huatai.datadevelop.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.datadevelop.entity.ApiSuperviseEntity;
import com.huatai.datadevelop.entity.InterfaceTableConfigEntity;
import com.huatai.datadevelop.mapper.InterfaceTableConfigMapper;
import com.huatai.datadevelop.utils.JDBCQueryUtil;
import com.huatai.datadevelop.utils.PageUtils;
import com.huatai.datadevelop.utils.Query;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class InterfaceTableConfigService extends ServiceImpl<InterfaceTableConfigMapper, InterfaceTableConfigEntity> {
    @Autowired
    private SyncImportService syncImportService;
    @Autowired
    private ApiSuperviseService apiSuperviseService;
    @Autowired
    private InterfaceTableConfigMapper interfaceTableConfigMapper;

    /**
     * 分页获取数据
     *
     * @param params
     * @return
     */
    public PageUtils queryPage(Map<String, Object> params) {
        String name = (String) params.get("name");
        IPage<InterfaceTableConfigEntity> page = this.page(
                new Query<InterfaceTableConfigEntity>().getPage(params),
                new QueryWrapper<InterfaceTableConfigEntity>().like(StringUtils.isNotBlank(name), "name", name)
        );
        return new PageUtils(page);
    }

    /**
     * 获取英文名称是否合规
     *
     * @param interfaceName
     * @return
     */
    public HashMap<String, Object> getTableNameCompliance(String interfaceName) {
        //判断接口名称是否为空
        if (StringUtils.isEmpty(interfaceName)) {
            throw new ServiceException("接口名称为空");
        }
        HashMap<String, Object> hashMap = new HashMap<>(2);
        hashMap.put("success", true);

        //判断是否全是英文
        boolean matches = interfaceName.matches("[a-zA-Z]+");
        if (!matches) {
            hashMap.put("success", false);
            hashMap.put("message", "只能填写英文");
            return hashMap;
        }
        QueryWrapper<InterfaceTableConfigEntity> qw = new QueryWrapper<>();
        qw.eq("interface_name", interfaceName);
        int count = (int) this.count(qw);
        if (count > 0) {
            hashMap.put("success", false);
            hashMap.put("message", "接口名称重复，请换一个");
            return hashMap;
        }
        hashMap.put("message", "验证通过");
        return hashMap;
    }

    /**
     * 根据表名称自动装配sql
     *
     * @param tableName
     * @return
     */
    public HashMap<String, String> getTableNameToSQL(String tableName) {
        HashMap<String, String> hashMap = this.syncImportService.getTableNameToSQL(tableName);
        return hashMap;
    }

    /**
     * 前端大屏调取数据
     *
     * @param params
     * @param entity
     * @param paramUrl page   limit
     * @return
     */
    public synchronized HashMap<String, Object> asyncRequestApi(Map<String, Object> params, InterfaceTableConfigEntity entity, HashMap<String, Object> paramUrl) {
        String type = "数据开放配置";
        ApiSuperviseEntity apiSuperviseEntity = new ApiSuperviseEntity();
        try {
            ApiSuperviseEntity interface_name = this.apiSuperviseService.getOne(new QueryWrapper<ApiSuperviseEntity>()
                    .eq("interface_name", entity.getInterfaceName())
                    .eq("type", type));
            if (interface_name != null) {
                apiSuperviseEntity = interface_name;
            }
        } catch (Exception ex) {
        }
        apiSuperviseEntity.setType(type);
        apiSuperviseEntity.setInterfaceName(entity.getInterfaceName());
        apiSuperviseEntity.setName(entity.getName());
        apiSuperviseEntity.setUrl("/ht-datadevelop/api/execute/asyncRequestApi/" + entity.getInterfaceName());
        apiSuperviseEntity.setSuperviseTime(new Date());

        HashMap<String, Object> retDa = new HashMap<>();
        List<HashMap<String, Object>> retData = new ArrayList<>();
        String sqlStr = entity.getSqlStr();
        //凭借where后面的参数  EQ(=), NE(!=), GE(>=), GT(>), LE(<=), LT(<), IN(in), NIN(not in),LIKE(like)
        String sqlPJ = " 1=1";
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                sqlPJ = sqlPJ + " and " + JDBCQueryUtil.querySQLStr(key, value);
            }
        }
        String limitStr = "";
        if (paramUrl != null && paramUrl.size() > 0) {
            Integer page = Integer.parseInt(paramUrl.get("page").toString());
            Integer limit = Integer.parseInt(paramUrl.get("limit").toString());
            limitStr = " limit " + (page - 1) * limit + " , " + limit + ";";

            //内置的sql语句
            Long tableNameCount = interfaceTableConfigMapper.getTableNameCount(sqlStr, sqlPJ);
            retDa.put("totalCount", tableNameCount);
        }
        List<HashMap<String, Object>> dataListInfoList = interfaceTableConfigMapper.getDataListInfoList(sqlStr, sqlPJ, limitStr);
        this.apiSuperviseService.executorService(apiSuperviseEntity);
        retDa.put("dataList", dataListInfoList);
        return retDa;
    }

    /**
     * 导入相关excel数据到指定的表格中
     * @param file
     * @throws IOException
     */
    public void importExcel(MultipartFile file, String tableId) throws IOException {
		this.syncImportService.importExcel(file, tableId);
    }
}
